package com.huilian.tool.douyin.applet.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.common.config.AppletDouYinConfig;
import com.huilian.tool.douyin.applet.service.DouYinAppletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class DouYinAppletServiceImpl implements DouYinAppletService {

    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private AppletDouYinConfig appletDouYinConfig;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    /**
     * 登录
     *
     * @param code 前端授权登录返回的code
     * @return
     */
    @Override
    public JSONObject jscode2session(String code) {
        StringBuilder url = new StringBuilder(appletDouYinConfig.getDeveloperUrl()).append("v2/jscode2session");
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appletDouYinConfig.getAppId());
        params.put("secret", appletDouYinConfig.getAppSecret());
        params.put("code", code);
        params.put("anonymous_code", "");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);

        /**
         * {
         *   "err_no": 0,
         *   "err_tips": "success",
         *   "data": {
         *     "session_key": "xyQ0nvauPAaE5R6TZWmpSg==",
         *     "openid": "_000jZ5ZMlaliDK8KXHe7p4jKcbBNnbRsjfq",
         *     "anonymous_openid": "",
         *     "unionid": "d41fcbdb-0fce-498e-b295-f5dcce14274a",
         *     "dopenid": ""
         *   }
         * }
         */
        return restTemplate.postForObject(url.toString(), entity, JSONObject.class);
    }

    @Override
    public String getDouYinAppletAccessToken(String redisKey) throws Exception {
        // RedisKey.DOU_YIN_APPLET_ACCESS_TOKEN
        String accessToken = (String) redisCacheTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(accessToken)) {
            JSONObject jsonObject = this.getAccessToken();
            if (jsonObject.getInteger("err_no").equals(0)) {
                JSONObject data = jsonObject.getJSONObject("data");
                accessToken = data.getString("access_token");
                redisCacheTemplate.opsForValue().set(redisKey, accessToken, 7100, TimeUnit.SECONDS);
            } else {
                throw new Exception("请求抖音accessToken失败！" + jsonObject);
            }
        }
        return accessToken;
    }

    private JSONObject getAccessToken() {
        StringBuilder url = new StringBuilder(appletDouYinConfig.getDeveloperUrl()).append("v2/token");
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appletDouYinConfig.getAppId());
        params.put("secret", appletDouYinConfig.getAppSecret());
        params.put("grant_type", "client_credential");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);
        return restTemplate.postForObject(url.toString(), entity, JSONObject.class);
    }
}
